package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import pojo.CommentArray;
import pojo.Comments;
import pojo.Note;
import service.*;
import service.impl.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;


@WebServlet("/noteServlet")
public class NoteServlet extends BaseServlet {
//    private FavouriteService favouriteService = new FavouriteServiceImpl();
//    private LabelService labelService = new LabelServiceImpl();
//    private NoteService noteService = new NoteServiceImpl();
//    private NoteLabelsService noteLabelsService = new NoteLabelsServiceImpl();
//    private CommentsService commentsService = new CommentsServiceImpl();
//    private CommentArrayService commentArrayService = new CommentArrayServiceImpl();
    //文件fail
//    /**
//     * 添加笔记
//     * @param req
//     * @param resp
//     * @throws ServletException
//     * @throws IOException
//     */
//    protected void addNote(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        req.setCharacterEncoding("utf-8");
//        //处理文件
//        if (ServletFileUpload.isMultipartContent(req)) {
//            FileItemFactory fileItemFactory = new DiskFileItemFactory();
//            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
//            //解析得到每一个表单项FileItem
//            List<FileItem> list = null;
//            //存储普通的表单项的
//            //Map<String,String> map=new HashMap<String,String>();
//            try {
//                list = servletFileUpload.parseRequest(req);
//            } catch (FileUploadException e) {
//                e.printStackTrace();
//            }
//            //每一个表单项普通类还是文件
//            for (FileItem fileItem : list) {
//                if (fileItem.isFormField()) {
//                    //String key=fileItem.getFieldName();
////String value=fileItem.getString("UTF-8");
////所有的普通表单项的数据全保存到map
//// map.put(key,value);
//                    if("title".equals(fileItem.getFieldName())) {
//                        String title=fileItem.getString("UTF-8");
//                    }
//                    if("type".equals(fileItem.getFieldName())) {
//                        String type=fileItem.getString("UTF-8");
//                    }
//                    if("content".equals(fileItem.getFieldName())) {
//                        String content=fileItem.getString("UTF-8");
//                    }
//                    if("labels".equals(fileItem.getFieldName())) {
//                        //String[] labels=req.getParameterValues("check");//直接打印只会得到数组的地址
//                        String labels=fileItem.getString("UTF-8");
////        //处理用户自定义标签
////        String[] userAddLabels =null;
////        userAddLabels=req.getParameterValues("userAddLabel");
//                    }
//
//
//                } else {
//                    //上传的文件
//                    System.out.println("表单项的name属性值：" + fileItem.getFieldName());
//                    System.out.println("上传的文件名：" + fileItem.getName());
//                    try {
//                        fileItem.write(new File("f:\\photos\\" + fileItem.getName()));
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }

    //        String usename=req.getParameter("usename");
//        System.out.println(usename);
//        String title=req.getParameter("title");
//        System.out.println(title);
//        String content=req.getParameter("content");
//        System.out.println(content);
//        String type=req.getParameter("type");
//        System.out.println(type);
//        String[] labels=req.getParameterValues("check");//直接打印只会得到数组的地址
//        for (String label : labels) {
//            System.out.println(label);
//        }
//        //处理用户自定义标签
//        String[] userAddLabels =null;
//        userAddLabels=req.getParameterValues("userAddLabel");
//        for (String userAddLabel : userAddLabels) {
//            System.out.println(userAddLabel);
//        }
//        if(userAddLabels.length==0||userAddLabels==null){
//            userAddLabels[0]="无";
//        }
//        Note noteadd=new Note();
//        noteadd.setStyle(0);
//        noteadd.setTitle(title);
//        noteadd.setContent(content);
//        noteadd.setType(type);
//        noteadd.setUsename(usename);
//        noteadd.setFavourite(0);
//        noteadd.setLikes(0);
//        NoteService noteService=new NoteServiceImpl();
//        boolean flag = noteService.addNote(noteadd);
//        System.out.println(flag);
//        if (flag == true) {
//            noteService.noteAddLabels(labels, userAddLabels, noteadd);
//            req.setAttribute("usename", usename);
//        }
//                if (!fileItem.isFormField()) {
//                    //上传的文件
//                    f小写小写小写！！！！！！！
//                    try {
//                        fileItem.write(new File("f:\\photos\\" + fileItem.getName()));
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        }
//        req.getRequestDispatcher("/pageServlet?action=userNotePage").forward(req, resp);
//    }


    protected String addNote(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        req.setCharacterEncoding("utf-8");
//                String usename = req.getParameter("usename");
//        String title = req.getParameter("title");
//        String content = req.getParameter("content");
//        String type = req.getParameter("type");
//        String[] labels = req.getParameterValues("check");//直接打印只会得到数组的地址！！！！！！
//        //处理用户自定义标签
//        String[] userAddLabels = req.getParameterValues("userAddLabel");
//        //int uid= Integer.parseInt(req.getParameter("uid"));
////        //标签处理
////        for (String label : labels) {
////            NoteLabels noteLabels=new NoteLabels();
////            int lid=labelService.findLabelLid(label);
////            int nid=noteService.findUserNoteNid(noteadd);
////            noteLabels.setNid(nid);
////            noteLabels.setLid(lid);
////        }
//        Note noteadd = new Note();
//        noteadd.setStyle(0);
//        noteadd.setTitle(title);
//        noteadd.setContent(content);
//        noteadd.setType(type);
//        noteadd.setUsename(usename);
//        noteadd.setFavourite(0);
//        noteadd.setLikes(0);
//        NoteService noteService = new NoteServiceImpl();
//        boolean flag = noteService.addNote(noteadd);
//        //System.out.println(flag);
//
//        if (flag == true) {
//            noteService.noteAddLabels(labels,userAddLabels,noteadd);
//            //标签处理
////            for (String label : labels) {
////                NoteLabels noteLabels = new NoteLabels();
////                int lid = labelService.findLabelLid(label);
////                int nid = noteService.findUserNoteNid(noteadd);
////                noteLabels.setNid(nid);
////                noteLabels.setLid(lid);
////                noteLabelsService.addNoteLabels(noteLabels);
////            }
////            //自定义标签处理
////            boolean isExist=false;
////
////            for (String userAddLabel : userAddLabels) {
////                int is=0;
////                NoteLabels addLabel = new NoteLabels();
////                //是否已存在该标签
////                isExist=labelService.labelIsExist(userAddLabel);
////                //未存在
////                if(isExist==false){
////                    labelService.addUserLabel(userAddLabel);
////                    //异常处理
////                }
////                for(int i=0;i<labels.length;i++){
////                    if(userAddLabels.equals(labels[i]))is=1;
////                }
////                if(is==0){
////                    int lidAdd = labelService.findLabelLid(userAddLabel);
////                    int nidAdd = noteService.findUserNoteNid(noteadd);
////                    addLabel.setLid(lidAdd);
////                    addLabel.setNid(nidAdd);
////                    noteLabelsService.addNoteLabels(addLabel);
////                }
////            }
//        req.setAttribute("usename", usename);
//        req.getRequestDispatcher("/pageServlet?action=userNotePage").forward(req, resp);
//    }else req.getRequestDispatcher("/pageServlet?action=userNotePage").forward(req,resp);
        String usename = req.getParameter("usename");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        String type = req.getParameter("type");
        String[] labels = req.getParameterValues("check");//直接打印只会得到数组的地址
        //处理用户自定义标签
        String[] userAddLabels = null;
        userAddLabels = req.getParameterValues("userAddLabel");
        if (userAddLabels.length == 0 || userAddLabels == null) {
            userAddLabels[0] = "无";
        }
        Note noteadd = new Note();
        noteadd.setStyle(0);
        noteadd.setTitle(title);
        noteadd.setContent(content);
        noteadd.setType(type);
        noteadd.setUsename(usename);
        noteadd.setFavourite(0);
        noteadd.setLikes(0);
        NoteService noteService = new NoteServiceImpl();
        boolean flag = noteService.addNote(noteadd);
        if (flag == true) {
            noteService.noteAddLabels(labels, userAddLabels, noteadd);
            req.setAttribute("usename", usename);
//            req.getRequestDispatcher("/pageServlet?action=userNotePage").forward(req, resp);
            return "g_/pageServlet?action=userNotePage";
        } else
//            req.getRequestDispatcher("/pageServlet?action=userNotePage").forward(req, resp);
            return "g_/pageServlet?action=userNotePage";
    }


    /**
     * 在用户笔记页删除笔记
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected String userDeleteNoteInUserNotes(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        String usename = req.getParameter("usename");
        int nid = Integer.parseInt(req.getParameter("nid"));
        NoteService noteService = new NoteServiceImpl();
        boolean flag = noteService.deleteNote(nid);
        if (flag) {
            req.setAttribute("usename", usename);
//            req.getRequestDispatcher("/pageServlet?action=userNotePage").forward(req, resp);
            return "g_/pageServlet?action=userNotePage";
        } else return "s_/error.jsp";
    }

    /**
     * 找到修改笔记
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected String findUpdateNote(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException, ClassNotFoundException {
        int nid = Integer.parseInt(req.getParameter("nid"));
        NoteService noteService = new NoteServiceImpl();
        Note notefind = new Note();
        notefind = noteService.findUpdateNote(nid);
        req.setAttribute("notefind", notefind);
//        req.getRequestDispatcher("/updateNote.jsp").forward(req, resp);
        return "g_/updateNote.jsp";
    }

    /**
     * 修改笔记
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected String userUpdateNote(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        req.setCharacterEncoding("utf-8");
        int nid = Integer.parseInt(req.getParameter("nid"));
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        String type = req.getParameter("type");
        String usename = req.getParameter("usename");
        Note note = new Note();
        note.setStyle(0);
        note.setNid(nid);
        note.setTitle(title);
        note.setContent(content);
        note.setType(type);
        note.setUsename(usename);
        note.setLikes(0);
        note.setFavourite(0);
        System.out.println(note);
        NoteService noteService = new NoteServiceImpl();
        boolean flag = noteService.updateNote(nid, note);
        System.out.println(flag);
//        req.getRequestDispatcher("/pageServlet?action=userNotePage").forward(req, resp);
        return "g_/pageServlet?action=userNotePage";
    }

    /**
     * 在未审核页删除笔记
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected String userDeleteNoteInCheckedNotes(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        String usename = req.getParameter("usename");
        int nid = Integer.parseInt(req.getParameter("nid"));
        NoteService noteService = new NoteServiceImpl();
        boolean flag = noteService.deleteNote(nid);
        if (flag) {
            req.setAttribute("usename", usename);
//            req.getRequestDispatcher("/pageServlet?action=userCheckedNotesPage").forward(req, resp);
            return "g_/pageServlet?action=userCheckedNotesPage";
        }
        return "s_/error.jsp";
    }

    /**
     * manager删除笔记
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected String managerDeleteNote(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        String nid = req.getParameter("nid");
        int nid1 = Integer.parseInt(nid);
        NoteService noteService = new NoteServiceImpl();
        String mid = req.getParameter("mid");
        boolean flag = noteService.deleteNote(nid1);
        if (flag) {
            req.setAttribute("nid", nid);
            req.setAttribute("mid", mid);
//            req.getRequestDispatcher("/pageServlet?action=managerAreaNotesPage").forward(req, resp);
            return "g_/pageServlet?action=managerAreaNotesPage";
        }
        return "s_/error.jsp";
    }

    /**
     * manager删除审核笔记
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected String managerDeleteCheckedNote(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        String nid = req.getParameter("nid");
        int nid1 = Integer.parseInt(nid);
        NoteService noteService = new NoteServiceImpl();
        boolean flag = noteService.deleteNote(nid1);
        String mid = req.getParameter("mid");
        if (flag) {
            req.setAttribute("nid", nid);
            req.setAttribute("mid", mid);
//            req.getRequestDispatcher("/pageServlet?action=managerCheckedNotesPage").forward(req, resp);
            return "g_/pageServlet?action=managerCheckedNotesPage";
        }
        return "s_/error.jsp";
    }

    /**
     * 通过审核笔记
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected String passNote(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        int mid = Integer.parseInt(req.getParameter("mid"));
        int nid = Integer.parseInt(req.getParameter("nid"));
        NoteService noteService = new NoteServiceImpl();
        boolean flag = noteService.passNote(nid);
        req.setAttribute("mid", mid);
//        req.getRequestDispatcher("/pageServlet?action=managerCheckedNotesPage").forward(req, resp);
        return "g_/pageServlet?action=managerCheckedNotesPage";
    }

    protected String likes(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        int nid = Integer.parseInt(req.getParameter("nid"));
        int uid = Integer.parseInt(req.getParameter("uid"));
        LikesService likesService = new LikesServiceImpl();
        boolean flag = false;
        flag = likesService.UserLikeNote(uid, nid);
        int number = likesService.noteLikes(nid);
        if (flag == true) {
//            req.getRequestDispatcher("/note.jsp").forward(req, resp);
            return "g_/note.jsp";
        }
        if (flag == false) {
//            req.getRequestDispatcher("/allAreas.jsp").forward(req, resp);
            return "g_/allAreas.jsp";
        }
        return "s_/error.jsp";
    }

    protected String unlikes(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        int nid = Integer.parseInt(req.getParameter("nid"));
        int uid = Integer.parseInt(req.getParameter("uid"));
        LikesService likesService = new LikesServiceImpl();
        boolean flag = false;
        flag = likesService.UserUnlikeNote(uid, nid);
        int number = likesService.noteLikes(nid);
        if (flag == true) {
//            req.getRequestDispatcher("/note.jsp").forward(req, resp);
            return "g_/note.jsp";
        }
        if (flag == false) {
//            req.getRequestDispatcher("/allAreas.jsp").forward(req, resp);
            return "g_/allAreas.jsp";
        }
        return "s_/error.jsp";
    }


    /**
     * 是否收藏
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void isFavourite(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        int nid = Integer.parseInt(req.getParameter("nid"));
        int uid = Integer.parseInt(req.getParameter("uid"));
        boolean flag = false;
        FavouriteService favouriteService = new FavouriteServiceImpl();
        flag = favouriteService.userFavouriteNote(uid, nid);
        int number = favouriteService.noteFavourites(nid);
        StringBuilder result = new StringBuilder();
        result.append("{")
                .append("\"flag\":" + flag)
                .append(",")
                .append("\"num\":" + number)
                .append("}");
        resp.setContentType("text/javascript");
        resp.getWriter().print(result.toString());
    }

    /**
     * 收藏笔记
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected String favourite(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        int nid = Integer.parseInt(req.getParameter("nid"));
        int uid = Integer.parseInt(req.getParameter("uid"));
        boolean flag = false;
        FavouriteService favouriteService = new FavouriteServiceImpl();
        flag = favouriteService.userFavouriteNote(uid, nid);
        int number = favouriteService.noteFavourites(nid);
        if (flag == true) {
//            req.getRequestDispatcher("/note.jsp").forward(req, resp);
            return "g_/note.jsp";
        }
        if (flag == false) {
//            req.getRequestDispatcher("/allAreas.jsp").forward(req, resp);
            return "g_/allAreas.jsp";
        }
        return "s_error.jsp";
    }

    /**
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected String unFavourite(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        int nid = Integer.parseInt(req.getParameter("nid"));
        int uid = Integer.parseInt(req.getParameter("uid"));
        boolean flag = false;
        FavouriteService favouriteService = new FavouriteServiceImpl();
        flag = favouriteService.UserUnFavourite(uid, nid);
        //int number = favouriteService.noteFavourites(nid);
        if (flag == true) {
//            req.getRequestDispatcher("/note.jsp").forward(req, resp);
            return "g_/note.jsp";
        }
        if (flag == false) {
//            req.getRequestDispatcher("/note.jsp").forward(req, resp);
            return "g_/note.jsp";
        }
        return "s_/error.jsp";
    }


//    @Deprecated
//    protected void allLabels(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException, ClassNotFoundException {
//        ArrayList<Label> allLabels = new ArrayList<>();
//        LabelService labelService = new LabelServiceImpl();
//        allLabels = labelService.allLabels();
//        req.setAttribute("allLabels", allLabels);
//    }

    /**
     * 笔记评论
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void comments(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException, ClassNotFoundException {
        int nid = Integer.parseInt(req.getParameter("nid"));
        ArrayList<CommentArray> commentWithChilden = new ArrayList<>();
        CommentsService commentsService = new CommentsServiceImpl();
        //父级评论
        ArrayList<Comments> commentsList = new ArrayList<Comments>();
        commentsList = commentsService.findCommentByNid(nid);
        resp.setContentType("text/javascript");

        @Deprecated
        //子级评论
        int cid = 0;
        for (Comments comments : commentsList) {
            CommentArray commentArray = new CommentArray();
            commentArray.setComments(comments);
            CommentArrayService commentArrayService = new CommentArrayServiceImpl();
            cid = comments.getCid();
            //该父评论的子评论
            commentArray.setChildComments(commentArrayService.findCommentChild(cid));
            commentWithChilden.add(commentArray);
        }
        //System.out.println(commentWithChilden);
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(resp.getOutputStream(), commentsList);
    }

    /**
     * 笔记子级评论
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void commentsChilden(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException, ClassNotFoundException {
        int cid = Integer.parseInt(req.getParameter("cid"));
        //System.out.println(cid);
        CommentArrayService commentArrayService = new CommentArrayServiceImpl();
        ArrayList<Comments> commentsChilden = commentArrayService.findCommentChild(cid);
        //子级评论
        resp.setContentType("text/javascript");
//        for (Comments comments : commentsList) {
//            CommentArray commentArray=new CommentArray();
//            commentArray.setComments(comments);
//            cid=comments.getCid();
//            //该父评论的子评论
//            commentArray.setChildComments(commentArrayService.findCommentChild(cid));
//            commentWithChilden.add(commentArray);
//        }
        // System.out.println(commentWithChilden);
        //System.out.println(commentsChilden);
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(resp.getOutputStream(), commentsChilden);
    }


    /**
     * 添加评论
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected String addComment(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        req.setCharacterEncoding("utf-8");
        int uid = Integer.parseInt(req.getParameter("uid"));
        int nid = Integer.parseInt(req.getParameter("nid"));
        String userComment = req.getParameter("comment");
        CommentsService commentsService = new CommentsServiceImpl();
        Comments comments = new Comments(uid, nid, userComment, null, 0, 0);
        boolean flag = false;
        flag = commentsService.addComment1(comments);
        req.setAttribute("nid", nid);
        req.setAttribute("uid", uid);
        if (flag == true)
//            req.getRequestDispatcher("/note.jsp").forward(req, resp);
            return "g_/note.jsp";
        else return "s_/error.jsp";
    }

    /**
     * 删除评论
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected String userDeleteComment(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException, ClassNotFoundException {
        req.setCharacterEncoding("utf-8");
        int cid = Integer.parseInt(req.getParameter("cid"));
        //System.out.println(cid);
        Comments comments = new Comments();
        CommentsService commentsService = new CommentsServiceImpl();
        comments = commentsService.findCommentByCid(cid);
        //System.out.println(comments);
        int nid = comments.getNid();
        //System.out.println(nid);
        int uid = comments.getUid();
        //System.out.println(uid);
        boolean flag = false;
        flag = commentsService.userDeleteComment(cid);
        //System.out.println(flag);
        req.setAttribute("nid", nid);
        req.setAttribute("uid", uid);
        if (flag == true)
//            req.getRequestDispatcher("/note.jsp?nid=" + nid + "&uid=" + uid).forward(req, resp);
            return "g_/note.jsp?nid=" + nid + "&uid=" + uid;
        else return "s_/error.jsp";
    }

}
